package com.sdy.usercenter.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.Response;
import com.sdy.common.utils.DateUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.mq.service.MqProducerService;
import com.sdy.mvc.controller.BaseController;
import com.sdy.mvc.utils.HttpUtil;
import com.sdy.mvc.utils.JsonUtil;
import com.sdy.usercenter.biz.constants.MqConstants;
import com.sdy.usercenter.biz.model.SysDept;
import com.sdy.usercenter.biz.model.SysLog;
import com.sdy.usercenter.biz.model.SysUser;
import com.sdy.usercenter.biz.service.SysDeptService;
import com.sdy.usercenter.biz.service.SysLogService;
import com.sdy.usercenter.biz.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zzq
 * @since 2019-06-14
 */
@Slf4j
@RestController
@RequestMapping("/sysLog")
public class SysLogController extends BaseController {
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private MqProducerService mqProducerService;
    @Autowired
    private SsoService ssoService;

    /**
     * 分页数据
     * @param request
     * @param page [current, size]
     * @return
     */
    @GetMapping("/pageData")
    public Response pageData(HttpServletRequest request, Page<SysLog> page, String id, Integer deptId, Integer type) throws Exception {
        LambdaQueryWrapper<SysLog> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(StringUtil.isNotBlank(id), SysLog::getId, id);

        wrapper.eq(deptId != null, SysLog::getDeptId, deptId);

        wrapper.eq(type != null, SysLog::getType, type);

        String opTimeRange0 = request.getParameter("opTimeRange[0]");
        String opTimeRange1 = request.getParameter("opTimeRange[1]");
        if (StringUtil.isNotBlank(opTimeRange0)) {
            wrapper = wrapper.between(SysLog::getOpTime,
                    DateUtil.getDate(opTimeRange0, DateUtil.DATETIME_FORMAT),
                    DateUtil.getDate(opTimeRange1, DateUtil.DATETIME_FORMAT));
        }

        wrapper.orderByDesc(SysLog::getId);

        IPage<SysLog> result = sysLogService.page(page, wrapper);
        if (!result.getRecords().isEmpty()) {
            // 补全用户信息
            List<Integer> userIdList = result.getRecords().stream().map(SysLog::getUserId).collect(Collectors.toList());
            Collection<SysUser> userList = sysUserService.listByIds(userIdList);
            if (!userIdList.isEmpty()) {
                Map<Integer, SysUser> userMap = new HashMap<>();
                userList.forEach(item -> userMap.put(item.getId(), item));
                result.getRecords().forEach(item -> {
                    SysUser user = userMap.get(item.getUserId());
                    if (user != null) {
                        item.setUserName(user.getName());
                    }
                });
            }
            // 补全部门信息
            List<Integer> deptIdList = result.getRecords().stream().map(SysLog::getDeptId).collect(Collectors.toList());
            Collection<SysDept> deptList = sysDeptService.listByIds(deptIdList);
            if (!deptList.isEmpty()) {
                Map<Integer, SysDept> deptMap = new HashMap<>();
                deptList.forEach(item -> deptMap.put(item.getId(), item));
                result.getRecords().forEach(item -> {
                    SysDept dept = deptMap.get(item.getDeptId());
                    if (dept != null) {
                        item.setDeptName(dept.getAbbreviation());
                    }
                });
            }
        }
        // 日志消息
        UserInfo opUserInfo = ssoService.getUserInfo(request);
        mqProducerService.send(MqConstants.Tags.TAG_OP_LOG,
                SysLog.LogType.QUERY_LOG.getTypeS().concat(MqConstants.SEP_TOKEN)
                        .concat(opUserInfo.getUserId().toString()).concat(MqConstants.SEP_TOKEN)
                        .concat(DateUtil.formatTime(new Date())).concat(MqConstants.SEP_TOKEN)
                        .concat(HttpUtil.getIpAddr(request)).concat(MqConstants.SEP_TOKEN)
                        .concat(opUserInfo.getUserName() + " 日志查询：参数=" + JsonUtil.toJson(request.getParameterMap()))
        );
        return Response.success(result);
    }
}
